package com.chengzhi.structure;

/**
 * @description: 并查集
 * @author: ruanchengzhi
 * @create: 2020-03-16 14:15
 **/
public class UnionFind {

    private int[] data;

    //根据节点size优化
    private int[] sz;

    private int[] rank;


    public UnionFind(int size) {
        data = new int[size];
        sz = new int[size];
        rank = new int[size];
        for (int i = 0; i < size; i++) {
            data[i] = i;
            sz[i] = 1;
            rank[i] = 1;
        }
    }

    private int find(int index) {
        while (index != data[index]) {
            index = data[index];
        }
        return index;
    }

    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }


    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }

        //根据节点size 判断合并
        /*if (sz[pRoot] < sz[qRoot]) {
            data[pRoot] = qRoot;
            sz[qRoot] += sz[pRoot];
        } else {
            data[qRoot] = pRoot;
            sz[pRoot] += sz[qRoot];
        }*/

        //根据rank优化
        if (rank[pRoot] < rank[qRoot]) {
            data[pRoot] = qRoot;
        } else if (rank[pRoot] > rank[qRoot]) {
            data[qRoot] = pRoot;
        } else {
            data[pRoot] = qRoot;
            rank[qRoot] += 1;
        }

    }
}
